﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace BluetoothMachine.ExpandHelper
{
    public static class NetworkHelper
    {
        /// <summary>
        /// 封装使用HttpClient调用WebService
        /// </summary>
        /// <param name="url">URL地址</param>
        /// <param name="o">对象</param>
        /// <returns></returns>
        public static async Task<string> PostHelper<T>(string url, T o) where T : new()
        {
            Dictionary<string, string> map = new Dictionary<string, string>();
            Type t = o.GetType();
            System.Reflection.PropertyInfo[] pi = t.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
            foreach (System.Reflection.PropertyInfo p in pi)
            {
                System.Reflection.MethodInfo mi = p.GetGetMethod();
                if (mi != null && mi.IsPublic)
                {
                    string str = mi.Invoke(o, new object[] { })?.ToString();
                    map.Add(p.Name, str ?? "");
                }
            }
            HttpContent content = new FormUrlEncodedContent(map);
            return await PostHelper(url, content);
        }

        /// <summary>
        /// 封装使用HttpClient调用WebService
        /// </summary>
        /// <param name="url">URL地址</param>
        /// <param name="content">HttpContent 对象</param>
        /// <returns></returns>
        public static async Task<string> PostHelper(string url, HttpContent content)
        {
            try
            {
                using (var client = new HttpClient())
                using (var response = await client.PostAsync(url, content))
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        return await response.Content.ReadAsStringAsync();
                        //XmlDocument doc = new XmlDocument();
                        //doc.LoadXml(result);
                        //Console.WriteLine(doc.DocumentElement["success"].InnerText);
                        //Console.WriteLine(doc.DocumentElement["errorMessage"].InnerText);
                        //Console.WriteLine(doc.DocumentElement["errorCode"].InnerText);
                    }
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            return null;
        }
    }
}
